package com.hawk.eye.server.controller.hawkeye;

import com.hawk.eye.client.toolkit.HawkEyeLogger;
import com.hawk.eye.common.constant.AuthConstant;
import com.hawk.eye.common.core.ApiResult;
import com.hawk.eye.common.encipher.MessageEncipher;
import com.hawk.eye.common.model.ServiceAuthData;
import com.hawk.eye.common.model.ServiceMetadata;
import com.hawk.eye.client.client.RequestParam;
import com.hawk.eye.framework.cache.ICache;
import com.hawk.eye.framework.utils.ExceptionUtils;
import com.hawk.eye.common.utils.JsonUtil;
import com.hawk.eye.server.auth.ServiceAuthHolder;
import com.hawk.eye.server.auth.ServiceAuthMetadata;
import com.hawk.eye.server.domain.vo.req.GroupReqVO;
import com.hawk.eye.server.service.IServiceAlarmService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.Map;

/**
 * 告警日志推送 Controller
 *
 * @author: salad
 * @date: 2023/9/30
 **/
@Slf4j
@RestController
@RequestMapping("/hawk-eye/service/")
@RequiredArgsConstructor
public class ServiceAlarmController {

    private final IServiceAlarmService serviceAlarmService;

    private final MessageEncipher messageEncipher;

    private final ICache cache;

    /**
     *
     */
    @GetMapping(value = "/testApi")
    public ApiResult testApi(String name) {
        log.error("测试一下", new RuntimeException());
        return ApiResult.ok("testApi");
    }

    /**
     *
     */
    @GetMapping(value = "/testApi2")
    public ApiResult testApi2(String name) {
        return ApiResult.ok(name);
    }

    /**
     *
     */
    @PostMapping(value = "/testApiPost")
    public ApiResult testApiPost(@RequestBody Map<String,String> params) {
        return ApiResult.ok(params);
    }

    /**
     *
     */
    @PostMapping(value = "/test")
    public ApiResult test() {
        log.error("测试");
        return ApiResult.ok("测试");
    }

    /**
     *
     */
    @PostMapping(value = "/test2")
    public ApiResult test2(@RequestBody GroupReqVO groupReqVO, String name) {
        return ApiResult.ok("测试");
    }

    /**
     *
     */
    @GetMapping(value = "/test2/file")
    public ApiResult file(MultipartFile file) {
        log.error("测试");
        return ApiResult.ok("测试");
    }


    /**
     * 颁发授权
     * @param requestParam 授权相关信息
     * @return
     */
    @PostMapping(value = "/push-metadata")
    public ApiResult<ServiceAuthData> pushMetadata(@RequestBody RequestParam requestParam) {
        ServiceMetadata serviceMetadata = requestParam.getServiceMetadata();
        ExceptionUtils.isEmptyThrow(serviceMetadata, "[ServiceMetadata]不能为空");
        ServiceAuthData sad = serviceAlarmService.pushMetadata(serviceMetadata);
        return ApiResult.ok(sad);
    }


    /**
     * 接收告警推送消息
     * @param requestParam 告警相关信息
     * @return
     */
    @PostMapping(value = "/push-alarm-log")
    public ApiResult pushAlarmLog(@RequestBody RequestParam requestParam) {
        try {
            serviceAlarmService.pushAlarmLog(requestParam);
        } catch (Throwable e) {
            HawkEyeLogger.errorWithSkipSend(this.getClass(), "告警日志存储异常：{}", e, e.getMessage());
            return ApiResult.fail("告警日志存储异常：" + e.getMessage());
        }
        return ApiResult.ok();
    }

    /**
     * RocketMQ接收告警推送消息
     */
    @Component
    @ConditionalOnProperty(value = "rocketmq.name-server")
    @RocketMQMessageListener(topic = "hawk_eye_topic", consumerGroup = "hawk_eye_consumer_group")
    public class RocketMqLogMessageConsumer implements RocketMQListener<MessageExt> {

        @Override
        public void onMessage(MessageExt message) {
            // 获取消息体
            String body = new String(message.getBody());
            // 获取自定义消息属性
            String token = message.getUserProperty(AuthConstant.HAWK_EYE_AUTH);
            if (token == null) {
                return;
            }
            ServiceAuthMetadata sam = cache.<ServiceAuthMetadata>get(token);
            if (sam == null) {
                return;
            }
            ServiceAuthHolder.setServiceAuthMetadata(sam);
            try {
                RequestParam requestParam = JsonUtil.parse(body, RequestParam.class);
                serviceAlarmService.pushAlarmLog(requestParam);
            } catch (Throwable e) {
                HawkEyeLogger.errorWithSkipSend(this.getClass(), "告警日志存储异常：{}", e, e.getMessage());
            }
        }
    }

}
